package vesko1.model;

import java.io.IOException;
import java.sql.SQLException;

public class BackupAndRestore {

    public static boolean backupDB(String path) {
        String executeCmd = "mysqldump -u " + DBConnection.username + " -p" + DBConnection.password
                + " --add-drop-database -B " + DBConnection.DBName + " -r " + path;
        Process runtimeProcess;
        try {
            System.out.println(executeCmd);//this out put works in mysql shell
            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            if (processComplete == 0) {
                System.out.println("Backup created successfully");
                return true;
            } else {
                System.out.println("Could not create the backup");
            }
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public static boolean restoreDB(String path) {
        try {
            DBConnection.getCon().createStatement().execute("DROP DATABASE "+ DBConnection.DBName);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        String executeCmd = "mysql -u " + DBConnection.username + " -p" + DBConnection.password + " < " + path;
        System.out.println(executeCmd);
        Process runtimeProcess;
        try {
            runtimeProcess = Runtime.getRuntime().exec("cmd.exe /c "+executeCmd);
            int processComplete = runtimeProcess.waitFor();
            if (processComplete == 0) {
                System.out.println("Database restored successfully");
                return true;
            } else {
                System.out.println("Could not restore the backup");
            }
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
        return false;
    }

}